package com.zxmr.asyn;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class AsynRequestRegister{

	static final int MAX_SEQUENCE = Integer.MAX_VALUE;
	static final int mapSize = 2000;
	static final ConcurrentHashMap<Integer,AsynRequest> contexts = 
						new ConcurrentHashMap<Integer,AsynRequest>(mapSize);
	static final AtomicInteger sequence = new AtomicInteger(0);
	static TaskMonitor monitor = null;
	
	public static int register(AsynRequest callback)
	{
		
		while(true)
		{
			int i = getNextSequence();
			add(i, callback);
			monitorRequest(callback);
			return i;
			
		}
	}
	
	private static void monitorRequest(AsynRequest callback) {
		if(monitor != null && callback.getTimeout() > 0)
		{
			AsynRequestMonitorCallBack arm = new AsynRequestMonitorCallBack(callback);
			monitor.addTask(arm, callback.getTimeout());
		}
	}
	private static void add(int i,AsynRequest callback)
	{
		contexts.put(i, callback);
	}
	private static int getNextSequence() {
		for(;;)
		{
            int current = sequence.get();
            int newValue = current + 1;
            if(newValue < 0 || newValue > Integer.MAX_VALUE)
            	newValue = 0;
            if (sequence.compareAndSet(current, newValue))
            	return newValue;
		}
	}
	public static void remove(int id)
	{
		contexts.remove(id);
	}
	public static AsynRequest getCallBack(int id)
	{
		return contexts.get(id);
	}
	public static boolean requestExist(int id)
	{
		return contexts.containsKey(id);
	}
	public static int getMaxSequence()
	{
		return MAX_SEQUENCE;
	}
	public static void setMonitor(TaskMonitor m)
	{
		monitor = m;
	}
}
